<template>
  <div>
    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 文章列表 -->
    <el-table :data="postList" style="width: 100%">
      <el-table-column label="ID" prop="id" width="50" />
      <el-table-column label="标题" prop="title" width="400" />
      <el-table-column label="作者" prop="user.nickname" width="150" />
      <el-table-column label="缩略图" width="200">
        <template slot-scope="scope">
          <img
            v-if="scope.row.cover.length"
            :src="formatUrl(scope.row.cover[0].url)"
            alt=""
            class="thumbnail"
          />
          <img v-else src="@/assets/logo.png" alt="" class="thumbnail" />
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.create_date.split("T")[0] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="$router.replace('/editpost?id=' + scope.row.id)"
            >编辑</el-button
          >
          <el-button type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "PostList",
  data() {
    return {
      postList: [],
      pageIndex: 1,
      pageSize: 2,
      total: 0,
    };
  },
  mounted() {
    this.getPostList();
  },
  methods: {
    getPostList() {
      this.$axios
        .get("/post", {
          params: {
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
          },
        })
        .then((res) => {
          // console.log(res)
          this.postList = res.data.data;
          this.total = res.data.total;
        });
    },
    handleCurrentChange(page) {
      this.pageIndex = page;
      this.getPostList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getPostList();
    },
    formatUrl(url) {
      const reg = /^http/;
      if (reg.test(url)) {
        return url;
      } else {
        return this.$axios.defaults.baseURL + url;
      }
    },
  },
};
</script>

<style scoped lang="less">
.thumbnail {
  width: 100%;
  object-fit: cover;
}
</style>
